package web;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应过滤器
 * 过滤响应中的敏感信息
 *
 * @author zdc
 */
@WebFilter("/*")
public class ResponseFilter implements Filter {

    /**
     * Filter初始化
     *
     * @param filterConfig Filter配置
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("SensitiveInfoFilter initialized");
    }

    /**
     * 处理响应
     *
     * @param request 请求对象
     * @param response 响应对象
     * @param chain Filter链
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        CharArrayWriter caw = new CharArrayWriter();
        PrintWriter writer = new PrintWriter(caw);
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(httpResponse) {
            public PrintWriter getWriter() {
                return writer;
            }
        };

        chain.doFilter(request, wrapper);
        String responseStr = caw.toString();

        // 过滤敏感信息
        String filteredResponseStr = filterSensitiveInfo(responseStr);
        response.getWriter().write(filteredResponseStr);
    }

    /**
     * 过滤敏感词
     *
     * @param text 文本
     * @return 过滤后的文本
     */
    private String filterSensitiveInfo(String str) {
        // 将所有的敏感词替换为"*"
        String sensitiveWord = "敏感词";
        return str.replaceAll(sensitiveWord, "*");
    }

    /**
     * 销毁 Filter
     */
    @Override
    public void destroy() {
        System.out.println("SensitiveInfoFilter destroyed");
    }
}

